import { reactive, watch } from "vue";
let sessionStore = reactive({
  enbled: true, //系统是否启用鉴权 false ,true
  data: null, // 示例:{user: null, permissions: null} //系统用户信息&系统权限列表
  //权限验证
  auth(permissionKey, permissionsData) {
    // console.log("[权限校验]", permissionKey, permissionsData, this);
    let enbled = this.enbled;
    if (!enbled) {
      // /console.warn("[权限校验][鉴权关闭]");
      return "AUTH_CLOSED";
    }
    //权限验证

    let permissions = permissionsData || (this.data || {}).permissions;
    if (!permissionKey || !permissions || !permissions.length) {
      return null;
    }
    let findPermission = function (tree, key) {
      for (const i in tree) {
        let node = tree[i];
        if (!node) {
          continue;
        }
        let code = node.code;
        let path = node.path;
        let permission = code == key || path == key ? node : findPermission(node.children, key);
        if (permission) {
          return permission;
        }
      }
    };
    return findPermission(permissions, permissionKey);
  }
});

function session(data) {
  data !== undefined && (sessionStore.data = data);
  return sessionStore.data;
}
session.store = sessionStore;
session.auth = function () {
  return sessionStore.auth(...arguments);
};
session.routeAuth = (fresh, old, router) => {
  router = router && router.replace ? router : location.hash;
  // console.log("[路由页面鉴权]", fresh, old, router);
  if (!sessionStore.enbled || !fresh || !router) {
    //鉴权关闭或没有路由或没有路由管理器则什么都不做
    // console.warn("[路由鉴权关闭]", fresh, old, router);
    return;
  }

  let sessionData = sessionStore.data || {};
  let user = sessionData.user; //用户信息
  let permissions = sessionData.permissions; //当前权限列表
  let path = fresh.path; //当前路由

  //用户未登录或已登陆但系统没任何权限
  if (!user || !permissions || !permissions.length) {
    console.log("[路由鉴权][用户未登录或没任何权限]");
    return path != "/login" && router.replace("/login").catch((error) => console.error(error)); //不在登陆页面跳转登陆页面
  }

  //用户已登录且有权限(同时处于登陆页面)则跳转首页
  if (path == "/login") {
    let menu = (permissions || []).flatMap((item) => [item, ...(item.children || [])]).filter((item) => item.path);
    let home = menu[0] || {};
    // console.log("[homePage]", home, menu, this.menu);
    let homeUrl = home.path || "/"; //获取首页地址
    console.log("[路由鉴权][用户已登录且有权限(同时处于登陆页面)则跳转首页]", homeUrl);
    return router.replace(homeUrl || "/").catch();
  }

  //当前页面没有权限(排除不需要鉴权的页面)
  let hasAuth = sessionStore.auth(path); //当前页面路由鉴权
  let pathIgnore = ["/", "/login", "/404", "/noAuth"]; //不需要鉴权的页面
  if (!hasAuth && !pathIgnore.includes(path)) {
    console.error(`[路由][${path}][没有对应权限]`);
    router.replace(`/noAuth?fromUrl=${fresh.fullPath}`).catch();
  } else {
    // console.log(`[路由鉴权通过]`,hasAuth);
  }
};
window.session = session;
export default session;

// // sessionStore.setSession(sessionOfServer); //初始化时同步服务端session
// app.config.globalProperties.$router.beforeEach((to, from, next) => {
//   console.log("[路由守卫]", to, from, this);
//   sessionStore.routeAuth(to, from);
//   next();
// });
